package com.sky.tesk;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，处理超时为支付订单与一直派送中的订单
 */
@Component

public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每分钟检查一次，当下单时间超过15分组，就需要修改状态，去取消订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processOrderTimeOut() {
        //     查询order表，条件状态-未支付 ，下单时间 < 当前时间-15分钟
        LocalDateTime ldtnow = LocalDateTime.now();
        LocalDateTime time = ldtnow.minusMinutes(15);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        if (ordersList == null || ordersList.size() <= 0) {
            return;
        }
        //     修改状态
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(ldtnow);
            orders.setCancelReason(MessageConstant.ORDER_TIME_OUT);
            ordersMapper.update(orders);
        });
    }


    /**
     * 每天流程1点检查是否存在派送中的任务，如果有就修改成已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliverOrder() {
        //     查询订单表状态，只找前一个小时的
        LocalDateTime ldtnow = LocalDateTime.now();
        LocalDateTime time = ldtnow.minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList == null || ordersList.size() <= 0) {
            return;
        }
        //     更新数据
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(ldtnow);
            ordersMapper.update(orders);
        });
    }

}
